<template>
  <div>
    <el-form :inline="true" :model="searchForm" ref="formRef">
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input v-model="searchForm.orderNumber" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="预订人" prop="orderUserName">
        <el-input v-model="searchForm.orderUserName" placeholder="请输入预订人" />
      </el-form-item>
      <el-form-item label="预定日期" prop="orderDate">
        <el-date-picker v-model="searchForm.orderDate" value-format="YYYY-MM-DD" type="date" placeholder="请选择预定日期"
          :disabled-date="disabledDate" :shortcuts="shortcuts" />
      </el-form-item>
      <el-form-item label="场地" prop="venueId">
        <el-select v-model="searchForm.venueId" placeholder="请选择场地">
          <el-option v-for="item in state.optionArea" :key="item.venueId" :label="item.venueName" :value="item.venueId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="searchForm.orderStatus" placeholder="请选择订单状态">
          <el-option v-for="item in state.optionOrderStatus" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="退款状态" prop="refundStatus">
        <el-select v-model="searchForm.refundStatus" placeholder="请选择订单状态">
          <el-option v-for="item in state.optionRefundStatus" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="发票状态" prop="invoiceStatus">
        <el-select v-model="searchForm.invoiceStatus" placeholder="请选择订单状态">
          <el-option v-for="item in state.optionInvoiceStatus" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getOrderInfo">查询</el-button>
        <el-button @click="onReset(formRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-bottom: 10px;display: flex;flex-direction: row;justify-content: space-between;">
      <el-button type="primary" @click="handleAddOrder" >添加订单</el-button>
      <ExportButton :path="AREA_ORDER_EXPORT_PATH" :fileName="AREA_ORDER_EXPORT_FILE_NAME" />
    </div> 
    <el-table :data="state.tableData" border style="width: 100%">
      <el-table-column prop="index" fixed="left" label="序号" width="60" />
      <el-table-column prop="orderNumber" label="订单编号" width="180" />
      <el-table-column label="订单状态" width="120">
        <template #default="scope">
          {{ OrderStatusEnumText[scope.row.orderStatus as OrderStatusEnum] }}
        </template>
      </el-table-column>
      <el-table-column label="退款状态" width="120">
        <template #default="scope">
          {{ RefundStatusEnumText[scope.row.refundStatus as RefundStatusEnum] }}
        </template>
      </el-table-column>
      <el-table-column label="开票状态" width="120">
        <template #default="scope">
          {{ InvoiceStatusEnumText[scope.row.invoiceStatus as InvoiceStatusEnum] }}
        </template>
      </el-table-column>
      <el-table-column prop="venueName" label="预定场馆" width="120" />
      <el-table-column prop="siteName" label="预定场地" width="120" />
      <el-table-column label="预定日期" width="120">
        <template #default="scope">
          {{ formatDate(new Date(scope.row.orderDate), "YYYY-mm-dd") }}
        </template>
      </el-table-column>
      <el-table-column label="预定时间" width="140">
        <template #default="scope">
          {{ scope.row.orderStartTime }} - {{ scope.row.orderEndTime }}
        </template>
      </el-table-column>
      <el-table-column prop="transactionAmount" label="金额" width="240">
        <template #default="scope">
          <div v-if="state.editPrice && state.editPriceIndex === scope.$index" class="flex-line">
            <el-input-number v-model="state.newPrice" :precision="2" :min="0.01" />
            <el-icon class="edit-price-icon" @click="submitEditPrice(scope.row.orderNumber)"><CircleCheck /></el-icon>
            <el-icon class="edit-price-icon" @click="cancelEditPrice"><CircleClose /></el-icon>
          </div>
          <div v-else>{{ scope.row.transactionAmount }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="orderUserName" label="预订人" />
      <el-table-column prop="phoneNumber" label="联系方式" width="120" />
      <el-table-column prop="peopleCount" label="踢球人数" width="120" />
      <el-table-column prop="remark" label="备注">
        <template #default="scope">
          {{ scope.row.remark === null ? '--' : scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="220">
        <template #default="scope">
          <el-button @click="handleDetail(scope.row, 'detail')">订单详情</el-button>
          <el-button v-if="scope.row.refundStatus === RefundStatusEnum.PENDING || scope.row.refundStatus === RefundStatusEnum.AUDITING
            " @click="handleDetail(scope.row, 'refund')">退款审核</el-button>
          <el-button v-if="scope.row.applyOrderInvoice === 'Y' && scope.row.invoiceStatus != InvoiceStatusEnum.COMPLETED"
            @click="handleDetail(scope.row, 'invoice')">发票审核</el-button>
          <el-button
              type="primary"
              v-show="scope.row.orderStatus === OrderStatusEnum.PENDING_PAYMENT"
              @click="editOrderPrice(scope.row, scope.$index)"
          >改价</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="state.total" :limit="state.pageSize" :page-change="PageChange" />
    <AddDialog ref="addDialogRef" :option="state.optionArea" @submitOrder="getOrderInfo" />
    <DetailDialog ref="detailDialogRef" :content="state.detailContent" />
    <RefundDialog ref="refundDialogRef" :content="state.detailContent" />
    <InvoiceDialog ref="InvoiceDialogRef" :content="state.detailContent" :invoice="state.invoiceInfo" />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { formatDate } from "@/utils/formatTime";
import AddDialog from "./Components/addDialog.vue";
import DetailDialog from "./Components/detailDialog.vue";
import RefundDialog from "./Components/refundDialog.vue";
import InvoiceDialog from "./Components/invoiceDialog.vue";
import Pagination from "@/components/pagination/index.vue";
import { getVenueSiteList, postOrderList, getInvoiceInfo, modifyAreaOrderAmount } from "@/api/area/index";
import { OrderStatusEnum, RefundStatusEnum, InvoiceStatusEnum } from "@/views/area/config/enum";
import { OrderStatusEnumText, RefundStatusEnumText, InvoiceStatusEnumText } from "@/views/area/config/index";
import ExportButton from '@/components/ExportButton/index.vue'
import { AREA_ORDER_EXPORT_PATH, AREA_ORDER_EXPORT_FILE_NAME } from '@/components/ExportButton/config'
import {modifyOrderAmount} from "@/api/shop";
import {ElMessage} from "element-plus";

const formRef = ref<FormInstance>();
const searchForm = reactive({
  orderNumber: "",
  orderUserName: "",
  venueId: "",
  orderDate: "",
  orderStatus: "",
  refundStatus: "",
  invoiceStatus: ""
});
const addDialogRef = ref();
const detailDialogRef = ref();
const refundDialogRef = ref();
const InvoiceDialogRef = ref();
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "上周",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
  {
    text: "上个月",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
      return date;
    },
  },
];
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};
const state = reactive({
  total: 10,
  pageNum: 1,
  pageSize: 10,
  tableData: [],
  optionArea: [],
  optionOrderStatus: [
    {
      label: "待支付",
      value: OrderStatusEnum.PENDING_PAYMENT,
    },
    {
      label: "支付成功",
      value: OrderStatusEnum.COMPLETED,
    },
    {
      label: "支付失败",
      value: OrderStatusEnum.FAILURE,
    },
    {
      label: "超时取消",
      value: OrderStatusEnum.CANCELED,
    },
  ],
  optionRefundStatus: [
    {
      label: "待处理",
      value: RefundStatusEnum.PENDING,
    },
    {
      label: "审核中",
      value: RefundStatusEnum.AUDITING,
    },
    {
      label: "通过",
      value: RefundStatusEnum.AUDIT_PASS,
    },
    {
      label: "审核不通过",
      value: RefundStatusEnum.AUDIT_NO_PASS,
    },
    {
      label: "退款完成",
      value: RefundStatusEnum.COMPLETED,
    },
  ],
  optionInvoiceStatus: [
    {
      label: "待处理",
      value: RefundStatusEnum.PENDING,
    },
    {
      label: "审核中",
      value: RefundStatusEnum.AUDITING,
    },
    {
      label: "开票完成",
      value: RefundStatusEnum.COMPLETED,
    },
  ],
  detailContent: {},
  invoiceInfo: {},
  editPrice: false, // 是否正在改价
  editPriceIndex: -1,
  newPrice: ''
});
// 添加订单
const handleAddOrder = () => {
  addDialogRef.value.dialogVisible = true;
};
// 订单详情
const handleDetail = (params: any, type: string) => {
  state.detailContent = params;
  if (type === "detail") {
    detailDialogRef.value.dialogVisible = true;
  } else if (type === "refund") {
    refundDialogRef.value.dialogVisible = true;
  } else if (type === "invoice") {
    getInvoice(params.orderVenueId)
    InvoiceDialogRef.value.dialogVisible = true;
  }
};
const onReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getOrderInfo();
};
// 获取发票数据
const getInvoice = (id: string) => {
  getInvoiceInfo({
    orderVenueId: id,
  }).then(res => {
    state.invoiceInfo = res.data || {}
  })
};
// 获取订单数据
const getOrderInfo = () => {
  postOrderList({
    pageNum: state.pageNum,
    pageSize: state.pageSize,
    extraParamMap: { ...searchForm, venueId: searchForm.venueId.toString() },
  }).then(res => {
    state.tableData = res.data.rows || []
    state.total = res.data.total || 0
    for (let i = 0; i < state.tableData.length; i++) {
      state.tableData[i].index = (state.pageNum - 1) * state.pageSize + i + 1
    }
  })
};
// 查询场地信息
const getAreaDate = () => {
  getVenueSiteList().then((res) => {
    state.optionArea = res.data || [];
    state.optionArea.map((item: any) => {
      item.siteList.map((it: any) => {
        it.venueId = it.venueSiteId
        it.venueName = it.siteName
      })
    })
  });
};
getAreaDate();
getOrderInfo();

// 待支付订单改价
const editOrderPrice = (row: any, index: number) => {
  state.editPrice = true
  state.editPriceIndex = index
  state.newPrice = row.transactionAmount
}

const submitEditPrice = (orderNumber: string) => {
  state.editPrice = false
  modifyAreaOrderAmount({
    orderNumber: orderNumber,
    transactionAmount: state.newPrice
  }).then(() => {
    ElMessage.success("改价成功");
    getOrderInfo()
    state.editPrice = false
  }).catch(() => {
    state.editPrice = false
  })
}

const cancelEditPrice = () => {
  state.editPrice = false
}

// 分页
const PageChange = (page: number) => {
  state.pageNum = page;
  getOrderInfo();
};
</script>

<style lang="scss" scoped>
.el-form .el-form-item:last-of-type {
  margin-bottom: 18px !important;
}
.flex-line {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.edit-price-icon {
  font-size: 20px;
  margin-left: 8px;
  cursor: pointer;
}
</style>
